package com.polidea.rxohosble2.sample.util;

import com.polidea.rxohosble2.RxBleClient;
import ohos.aafwk.ability.Ability;
import ohos.bundle.IBundleManager;

public class LocationPermission {

    private LocationPermission() {
        // Utility class
    }

    private static final int REQUEST_PERMISSION_BLE_SCAN = 9358;

    public static void requestLocationPermission(final Ability ability, final RxBleClient client) {
        if (ability.verifySelfPermission("ohos.permission.LOCATION") != IBundleManager.PERMISSION_GRANTED) {
            if (ability.canRequestPermission("ohos.permission.LOCATION")) {
                ability.requestPermissionsFromUser(
                        new String[]{"ohos.permission.LOCATION"}, REQUEST_PERMISSION_BLE_SCAN);
            }
        }
    }

    public static boolean isRequestLocationPermissionGranted(final int requestCode, final String[] permissions,
                                                             final int[] grantResults, RxBleClient client) {
        if (requestCode != REQUEST_PERMISSION_BLE_SCAN) {
            return false;
        }

        String[] recommendedScanRuntimePermissions = client.getRecommendedScanRuntimePermissions();
        for (int i = 0; i < permissions.length; i++) {
            for (String recommendedScanRuntimePermission : recommendedScanRuntimePermissions) {
                if (permissions[i].equals(recommendedScanRuntimePermission)
                        && grantResults[i] == IBundleManager.PERMISSION_GRANTED) {
                    return true;
                }
            }
        }

        return false;
    }
}
